package com.hui.auth.config.shiro;

import com.hui.auth.config.shiro.filter.KickoutSessionFilter;
import com.hui.auth.config.shiro.filter.LoginFilter;
import com.hui.auth.config.shiro.filter.PermissionFilter;
import com.hui.auth.config.shiro.session.CustomSessionRedisDao;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.Filter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Shiro配置
 *
 * @author 廖云辉
 * @apiNote http://ask.csdn.net/questions/652023
 */
@Configuration
public class ShiroConfig {

    /**
     * 定义shiro拦截器，用来告诉shiro哪些url需要权限判断，哪些url不用判断
     */
    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(manager);
        //配置登录的url和登录成功的url
        bean.setLoginUrl("/auth/login");
        /*自定义过滤器*/
        Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
        filters.put("login", new LoginFilter());//登录拦截
        filters.put("simplePerms", new PermissionFilter());//权限拦截
        filters.put("kickout", new KickoutSessionFilter());//单点登录处理
        bean.setFilters(filters);
        /**
         * 加载shiroFilter权限控制规则（从数据库读取然后配置）
         * @apiNote http://blog.csdn.net/wangshfa/article/details/40344053
         * <p>
         * 其权限过滤器及配置释义：
         * @anon 例子/admins/**=anon 没有参数，表示可以匿名使用。
         * @authc 例如/admins/user/**=authc表示需要认证(登录)才能使用，没有参数
         * @roles 例子/admins/user/**=roles[admin],参数可以写多个，多个时必须加上引号，并且参数之间用逗号分割，
         * 当有多个参数时，例如admins/user/**=roles["admin,guest"],每个参数通过才算通过，相当于hasAllRoles()方法。
         * @perms 例子/admins/user/**=perms[user:add:*],参数可以写多个，多个时必须加上引号，并且参数之间用逗号分割，
         * 例如/admins/user/**=perms["user:add:*,user:modify:*"]，当有多个参数时必须每个参数都通过才通过，想当于isPermitedAll()方法。
         * @rest 例子/admins/user/**=rest[user],根据请求的方法，相当于/admins/user/**=perms[user:method] ,
         * 其中method为post，get，delete等。
         * @port 例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,
         * 其中schmal是协议http或https等，serverName是你访问的host,8081是url配置里port的端口，queryString是你访问的url里的？后面的参数。
         * @authcBasic 例如/admins/user/**=authcBasic没有参数表示httpBasic认证
         * @ssl 例子/admins/user/**=ssl没有参数，表示安全的url请求，协议为https
         * @user 例如/admins/user/**=user没有参数表示必须存在用户，当登入操作时不做检查
         * </p>
         */
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//        filterChainDefinitionMap.put("/user/**", "roles[系统管理员]");//系统默认角色权限判断，用起来不方便
//        filterChainDefinitionMap.put("/auth/user/**", "simplePerms");//自定义权限拦截器
        filterChainDefinitionMap.put("/auth/test_callable**", "anon");
        filterChainDefinitionMap.put("/swagger**", "anon");
        filterChainDefinitionMap.put("/swagger-resources/**", "anon");
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/v2/**", "anon");
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
        filterChainDefinitionMap.put("/favicon.ico**", "anon");
        filterChainDefinitionMap.put("/static/**", "anon");
//        filterChainDefinitionMap.put("/auth/user/select", "anon");
//        filterChainDefinitionMap.put("/**", "login,kickout,simplePerms");
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }

    /**
     * 配置核心安全事务管理器
     */
    @Bean(name = "securityManager")
    public SecurityManager securityManager(
            @Qualifier("sessionManager") SessionManager sessionManager,
            @Qualifier("authRealm") AuthRealm authRealm) {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(authRealm);
        manager.setSessionManager(sessionManager);
        return manager;
    }

    /**
     * 配置自定义的权限登录器
     */
    @Bean(name = "authRealm")
    public AuthRealm authRealm(@Qualifier("credentialsMatcher") CredentialsMatcher matcher) {
        AuthRealm authRealm = new AuthRealm();
        authRealm.setCredentialsMatcher(matcher);
        return authRealm;
    }

    /**
     * 配置自定义sessionManager
     */
    @Bean(name = "sessionManager")
    public WebSessionManager sessionManager(@Qualifier("customSessionRedisDao") CustomSessionRedisDao sessionRedisDao) {
        DefaultWebSessionManager manager = new DefaultWebSessionManager();
        manager.setSessionDAO(sessionRedisDao);
        return manager;
    }

    /**
     * 配置自定义的密码比较器
     */
    @Bean(name = "credentialsMatcher")
    public CredentialsMatcher credentialsMatcher() {
        return new CredentialsMatcher();
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }

    /**
     * 开启shiro aop注解支持.
     * 使用代理方式;所以需要开启代码支持;
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager manager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(manager);
        return advisor;
    }

    /**
     * 配置过滤器
     * <p>
     * 在spring-web中定义在web.xml里
     * 加载顺序：listener——filter——servlet
     * 所有传统的filter不能使用spring注解，该配置为代理filter，可以在filter中使用spring的注解配置
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
        filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
        //  该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
        filterRegistration.addInitParameter("targetFilterLifecycle", "true");
        filterRegistration.setEnabled(true);
        filterRegistration.setOrder(1);//执行顺序
        List<String> urlPatterns = new ArrayList<String>();
        urlPatterns.add("/*");
        filterRegistration.setUrlPatterns(urlPatterns);
        return filterRegistration;
    }

}
